package com.example.firstapp;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.appcompat.app.AppCompatActivity;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Music01Activity extends AppCompatActivity {
    static List<Map<String, Object>> items = new ArrayList<>();
    ListView lv_music;
    static ArrayList<String> songList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music01);
        //动态获取权限
        runtimePermission();

        //绑定组件
        lv_music = findViewById(R.id.lv_music);
        updateList();

        //播放列表点击监听
        lv_music.setOnItemClickListener((adapterView, view, i, l) -> {
            Intent intent = new Intent(Music01Activity.this, Music02Activity.class);
            intent.putExtra("songList", songList);
            intent.putExtra("index", i);
            startActivity(intent);
        });
    }

    //获取音乐文件列表
    public static void getMusic(String path) {
        File file = new File(path);
        songList.clear();
        if (file.isDirectory()) {
            File[] array = file.listFiles();
            assert array != null;
            for (File f : array) {
                String song = f.toString();
                String[] arr = song.trim().split("\\.");
                if (Objects.equals(arr[arr.length - 1], "mp3")) {
                    songList.add(song);
                }
            }
        }
    }

    //权限获取
    public void runtimePermission() {
        Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
                        permissionToken.continuePermissionRequest();
                    }
                }).check();
    }

    //更新列表
    public void updateList() {
        getList();
        SimpleAdapter adapter = new SimpleAdapter(Music01Activity.this,
                items,
                R.layout.list_item,
                new String[]{"ico", "song", "singer"},
                new int[]{R.id.lv_img, R.id.tv_lv_name, R.id.tv_lv_text});
        lv_music.setAdapter(adapter);
    }

    public void getList() {
        getMusic("data/data/com.example.firstapp/music");
//        getMusic(Music01Activity.this);
        items.clear();
        for (String s : songList) {
            Map<String, Object> m = new HashMap<>();
            String[] arr = s.trim().split("/");
            String name = arr[arr.length - 1];
            Log.i("music", name);
            String singer = name.trim().split("-")[0].trim();
            String song = name.trim().split("-")[1].trim().split("\\.")[0];
            m.put("ico", R.drawable.music);
            m.put("song", song);
            m.put("singer", singer);
            items.add(m);
        }
    }

    public static void getMusic(Context context) {
        songList.clear();
        try {
            Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                    , null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
            if (cursor != null) {
                Log.i("music", "列表长度：" + cursor.getCount());
                while (cursor.moveToNext()) {
                    String uri = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    String[] tmp = uri.split("\\.");
                    if (Objects.equals(tmp[tmp.length - 1], "mp3")) {
                        songList.add(uri);
                        Log.i("music", "歌名:" + cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
                    }
                }
                cursor.close();
            } else
                Log.i("music", "列表空");
        } catch (Exception e) {
            Log.i("music", "error:" + e);
        }
    }
}